import axios from 'axios';

// 根据环境自动选择API地址
let baseURL = '';
if (process.env.NODE_ENV === 'development') {
  // 开发环境：直接访问后端端口
  baseURL = 'http://localhost:8001/api/journal';
} else {
  // 生产环境：通过nginx代理
  baseURL = '/api/journal';
}

const instance = axios.create({
  baseURL,
});

instance.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.token = token;
  }
  return config;
});

instance.interceptors.response.use(
  res => res,
  err => {
    if (err.response && err.response.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('username');
      window.location.reload();
    }
    return Promise.reject(err);
  }
);

export default instance;